package it.unisa.unibox.commons;

import java.io.InputStream;
import java.sql.Connection; //TODO:oppure import com.mysql.jdbc.Connection ???
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * Una classe di metodi statici per la configurazione e la connessione con il
 * DBMS MySql
 * 
 * @author raffaele
 * 
 */
public class DBConnection {

	static Properties dbProperties;
	static DBConnection dbConnection;

	/**
	 * Singleton pattern, ritorna un'istanza dell'oggetto
	 * @return l'oggetto
	 */
	public static DBConnection getInstance() {
		if (dbConnection == null)
			dbConnection = new DBConnection();
		return dbConnection;
	}
	
	public static void main(String[] args){
		connDB();
	}
	
	public static void connDB() {
		try {

			// Per prelevare le informazioni di connessione al db del file db.properties 
			// In caso di problemi far riferimento al capitolo 5 del documento Unibox_MI			
			InputStream fileProperties = DBConnection.class.getClassLoader().getResourceAsStream("/db.properties");
			DBConnection.dbProperties = new Properties();
			DBConnection.dbProperties.load(fileProperties);

			// Per inserire manualmente le impostazioni di connessione al db
			
 /*			DBConnection.dbProperties = new Properties();
			DBConnection.dbProperties.setProperty("driver", "com.mysql.jdbc.Driver");
			DBConnection.dbProperties.setProperty("url", "jdbc:mysql://localhost/db_unibox");
			DBConnection.dbProperties.setProperty("username", "root");
			DBConnection.dbProperties.setProperty("password", "");	
	*/	
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			DBMS_CONNECTION = DriverManager.getConnection(
					DBConnection.dbProperties.getProperty("url"),
					DBConnection.dbProperties.getProperty("username"),
					DBConnection.dbProperties.getProperty("password"));

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void disconnDBr() throws SQLException {
		DBMS_CONNECTION.close();
	}

	public static ResultSet execQuery(String query) throws SQLException {

		if(DBMS_CONNECTION==null) connDB();

		Statement st = DBMS_CONNECTION.createStatement();
		ResultSet rs = st.executeQuery(query);
		return rs;
	}

	public static int execUpdate(String query) throws SQLException {
		if(DBMS_CONNECTION==null) connDB();

		Statement st = DBMS_CONNECTION.createStatement();
		int ret = st.executeUpdate(query);
		return ret;
	}

	private static Connection DBMS_CONNECTION = null;
}
